package com.yin.myproject.thread;

import java.util.concurrent.Semaphore;

/**
 * @author Eason
 * @create 2018-03-21 14:59
 **/
public class SemaphoreUsecase {
    private Semaphore semaphore = new Semaphore(2);

    public void race() throws InterruptedException {
        System.out.println("Thread " + Thread.currentThread().getName() + " is waiting the resource");
//        semaphore.acquireUninterruptibly();
        semaphore.acquire();
        try{
            System.out.println("Thread " + Thread.currentThread().getName() + " got the resource");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }finally{
            System.out.println("Thread " + Thread.currentThread().getName() + " is releasing the resource");
            semaphore.release();
        }
    }

    public static void main(String[] args){
        final SemaphoreUsecase usecase = new SemaphoreUsecase();

        for(int i = 0; i < 10; i++){
            Thread t = new Thread(() -> {
                try {
                    usecase.race();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i));
            t.start();
        }
    }
}
